import {GptVersion} from "@/app/constants";
import {MessageRole} from "@/types/chat";
import {useAccessStore} from "@/app/store/access";
import {getServerSideConfig} from "@/app/config/server";

// 构建前把localhost修改为你的公网IP或者域名地址
let {apiHostUrl} = getServerSideConfig();
// apiHostUrl = "http://localhost:8080";
apiHostUrl = "https://www.jzzzb.top";

/**
 * Header 信息
 */
function getHeader() {
    const accessState = useAccessStore.getState();
    return {
        Authorization: accessState.token,
        "Content-Type": "application/json;charset=utf-8"
    }
}

/**
 * Role 角色获取接口
 */
export const getRoleList = async () => {
    // 从本地 json 文件获取
    return fetch(`/prompts.json`).then((res) => res.json());
}

/**
 * 流式应答接口
 */
export const completions = (data: {
    model: GptVersion,
    messages: { role: MessageRole, content: string }[]
}) => {
    console.log(apiHostUrl);
    return fetch(`${apiHostUrl}/api/v1/chatgpt/chat/completions`, {
        method: 'post',
        headers: getHeader(),
        body: JSON.stringify(data)
    });
}

/**
 * 登录鉴权接口
 */
export const doLogin = () => {
    const accessState = useAccessStore.getState();
    return fetch(`${apiHostUrl}/api/v1/auth/login`, {
        method: 'post',
        headers: {
            "Content-Type": "application/x-www-form-urlencoded"
        },
        body: `code=${accessState.accessCode}`
    });
}

/**
 * 查询商品列表接口
 */
export const queryProductList = () => {
    return fetch(`${apiHostUrl}/api/v1/sale/query_product_list`, {
        method: 'get',
        headers: getHeader()
    });
}

/**
 * 用户商品下单接口，获得支付地址 url
 */
export const createPayOrder = (productId: number) => {
    return fetch(`${apiHostUrl}/api/v1/sale/create_pay_order`, {
        method: 'post',
        headers: {
            ...getHeader(),
            "Content-Type": "application/x-www-form-urlencoded;charset=utf-8"
        },
        body: `productId=${productId}`
    })
}
